<?php

/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2023/9/18 11:29
 * Desc: 会员钱包
 */
class Service_Api_Member_Bag extends Contract_Api_Member_Bag
{

    public function withdraw_way(): array
    {
        $way = Model_Sysconfig::get_configs(0, 'cfg_member_withdraw_way', true);
        return $way ? explode(',', $way) : array();
    }

    public function wallet_index(int $mid): array
    {
        $member                     = Model_Member::get_member_info($mid);
        $data['cash_available_num'] = Model_Member_Withdraw::get_available_num($mid);
        // 计算可提现金额
        $money                  = St_Math::sub(array($member['money'], $member['money_frozen']), 2);
        $money                  = max($money, 0);
        $data['money']          = Currency_Tool::price($money);

        if(St_Functions::is_normal_app_install('system_wallet')){
            $wallet_member = DB::select()->from('wallet_member')->where('member_id', '=', $mid)->execute()->current();
            $data['wallet_balance'] = $wallet_member['remain_amount']?:0;
            $data['total_balance']  = bcadd($data['money'], $data['wallet_balance'], 2);
        }else{
            $data['wallet_balance'] = $data['money'];
            $data['total_balance']  = $data['money'];
        }

        return $data;
    }

    public function withdraw_audit(int $mid, array $params): array
    {
        /**
         * @var $bank_card_number
         * @var $bank_account_name
         * @var $withdraw_amount
         * @var $way
         * @var $bank_name
         * @var $description
         */
        extract($params);

        $config          = Model_Member_Withdraw::get_config();
        $withdraw_amount = floor(doubleval($withdraw_amount) * 100) / 100;

        if ($config['cash_min'] == 1 && $withdraw_amount < $config['cash_min_num']) {
            throw new Exception("申请金额不足最低限度{$config['cash_min_num']}");
        }

        if ($withdraw_amount < 0.1) {
            throw new Exception('申请金额不能低于0.1');
        }

        if (Model_Member_Withdraw::get_available_num($mid) == 0) {
            throw new Exception('当月可提现次数已用完');
        }

        $member       = Model_Member::get_member_info($mid);
        $useful_money = bcsub($member['money'], $member['money_frozen'], 2);
        if ($useful_money < $withdraw_amount) {
            throw new Exception('可提现余额不足');
        }

        $withdraw_model                  = ORM::factory('member_withdraw');
        $withdraw_model->memberid        = $mid;
        $withdraw_model->withdrawamount  = $withdraw_amount;
        $withdraw_model->bankname        = $bank_name ?? '';
        $withdraw_model->way             = $way;
        $withdraw_model->bankcardnumber  = $bank_card_number;
        $withdraw_model->bankaccountname = $bank_account_name;
        $withdraw_model->description     = $description ?? '';
        $withdraw_model->status          = 0;
        $withdraw_model->addtime         = time();
        $withdraw_model->save();
        if (!$withdraw_model->saved()) {
            throw new Exception('提现失败，请重试');
        }
        $withdraw_model->reload();
        $withdraw_id = $withdraw_model->id;

        //会员信息修改
        $member_model               = ORM::factory('member', $mid);
        $member_model->money_frozen += $withdraw_amount;
        $member_model->save();
        if (!$member_model->saved()) {
            throw new Exception('提现失败，请重试');
        }

        // 添加提现记录
        Model_Member_Cash_Log::add_log($mid, 2, $withdraw_amount, "提交提现申请后冻结{$withdraw_amount}元", array('withdrawid' => $withdraw_id));

        switch ($way) {
            case 'bank':
                $way='银行卡';
                break;
            case 'alipay':
                $way='支付宝';
                break;
            case 'weixin':
                $way='微信';
                break;
        }
        $withdraw_info=[
            'username'=>$member['nickname'],
            'mobile'=>$member['mobile'],
            'withdraw_type'=>$way,
            'withdraw_status'=>'申请提现',
            'withdraw_addtime'=>date('Y-m-d H:i:s',$withdraw_model->addtime),
        ];
        Hook::trigger('withdraw_create', $withdraw_info);

        return array('id' => $withdraw_id);
    }

    public function withdraw_record(int $mid, array $params): array
    {
        /**
         * @var $page
         * @var $pagesize
         * @var $status
         * @var $way
         */
        extract($params);

        $builder = DB::select('id', 'way', 'status', 'addtime', DB::expr('withdrawamount as withdraw_amount'))
            ->from('member_withdraw')
            ->where('memberid', '=', $mid);

        if (!empty($way)) {
            $builder->where('way', '=', $way);
        }

        if (isset($params['status'])) {
            $builder->where('status', '=', $status);
        }

        $total = $builder->execute()->count();

        $offset = St_Page::offset($page, $pagesize);
        $list   = $builder->limit($pagesize)
            ->offset($offset)
            ->order_by('addtime', 'desc')
            ->execute()
            ->as_array();

        foreach ($list as $k => $v) {
            $list[$k]['addtime']         = date('Y-m-d H:i:s', $v['addtime']);
            $list[$k]['withdraw_amount'] = Currency_Tool::price($v['withdraw_amount']);
        }

        return array('total' => $total, 'list' => $list);
    }

    public function record_info(int $mid, int $id): array
    {
        $data = DB::select('id', 'way', 'status', 'addtime', 'audit_description', 'description',
            DB::expr('withdrawamount as withdraw_amount,bankname as bank_name,bankcardnumber as bank_card_number,bankaccountname as bank_account_name')
        )
            ->from('member_withdraw')
            ->where('id', '=', $id)
            ->and_where('memberid', '=', $mid)
            ->execute()
            ->current();

        if (empty($data)) {
            throw new Exception('记录不存在');
        }

        $data['addtime']           = date('Y-m-d H:i', $data['addtime']);
        $data['audit_description'] = $data['audit_description'] ?: '';
        $data['withdraw_amount']   = Currency_Tool::price($data['withdraw_amount']);

        return $data;
    }

    public function cash_log(int $mid, array $params): array
    {
        /**
         * @var $page
         * @var $pagesize
         * @var $type
         */
        extract($params);

        $builder = DB::select('id', 'type', 'amount', 'description', 'addtime', DB::expr('withdrawid as withdraw_id,orderid as order_id'))
            ->from('member_cash_log')
            ->where('memberid', '=', $mid);
        if (isset($params['type']) && $params['type'] != '') {
            $builder->where('type', '=', $type);
        }
        $total = $builder->execute()->count();

        $offset = St_Page::offset($page, $pagesize);
        $list   = $builder->limit($pagesize)
            ->offset($offset)
            ->order_by('addtime', 'desc')
            ->execute()
            ->as_array();

        foreach ($list as $k => $v) {
            $list[$k]['addtime']  = date('Y-m-d H:i:s', $v['addtime']);
            $list[$k]['order_id'] = $v['order_id'] ?: '';
            $list[$k]['amount']   = Currency_Tool::price($v['amount']);
        }

        return array('total' => $total, 'list' => $list);
    }
}